/* 
 * [New BSD License (BSD 3-Clause License)]
 * Copyright (c) 2012, Max Bechtold
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 *     - Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     - Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     - Neither the name of the Rel2Xml Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package maxbe.rel2xml.generator.docs.constraints;

import java.util.List;
import java.util.Random;

import maxbe.rel2xml.grammar.FillTableException;

import org.apache.log4j.Logger;

/**
 * Describes a partial data constraint like "... with first 5% as null".</br>
 * Consider this example: If global is specified, the first 5% of all generated
 * values will be null.</br> Otherwise, the context is the same as that of the
 * main ValueConstructor of the column (e.g. as 'unique number per A' where the
 * table of this PartialConstraint's column directly depends on A will deliver
 * null values for the first 5% of the values constructed in the context of each
 * A value).</br> If the main ValueConstructor of the column has not specified a
 * context, the PartialConstraints can do so. If it doesn't, the partialContext
 * will be the lowest context possible and switch with every mark method
 * invocation.
 * 
 * 
 * @author Max Bechtold
 * 
 */
public class PartialConstraint {

	private static Logger log = Logger.getLogger(PartialConstraint.class);

	private final int percentage;

	/**
	 * Effective percentage due to first/last PartialConstraints diminishing the
	 * whole
	 */
	private float effPercentage = -1;

	/**
	 * States whether this first or last PartialConstraint will be called once
	 * or in each context
	 */
	private boolean global;

	/**
	 * If the PartialConstraint is to derive count from the context size
	 * communicated via the mark method or whether it is set due to aggregated
	 * filling factors
	 */
	private boolean deriveBoundary = true;

	private final ValueConstructor valueConstructor;

	private final Random rand;

	/** Describes a boundary count for first and last PartialConstraints */
	private int boundary;

	private int offsetRemainder;

	private static long seed = 443761238;

	public PartialConstraint(int percentage, boolean global,
			ValueConstructor valueConstructor) {
		if (valueConstructor instanceof References) {
			String msg = "Cannot have References as ValueConstructor of a PartialConstraint, only of a DataConstraint";
			log.error(msg);
			throw (new FillTableException(msg));
		}

		this.valueConstructor = valueConstructor;
		this.percentage = percentage;
		this.global = global;
		rand = new Random(seed++);

		checkPercentage(percentage);
	}

	public boolean isGlobal() {
		return global;
	}

	public int getBoundary() {
		return boundary;
	}

	public boolean derivesBoundary() {
		return deriveBoundary;
	}

	public ValueConstructor getValueConstructor() {
		return valueConstructor;
	}

	public int getPercentage() {
		return percentage;
	}

	public void setGlobal(boolean global) {
		this.global = global;
	}

	public void setBoundary(int count) {
		this.boundary = count;
	}

	public void setDeriveBoundary(boolean deriveCount) {
		this.deriveBoundary = deriveCount;
	}

	public float getEffPercentage() {
		return effPercentage;
	}

	public void setEffPercentage(float effPercentage) {
		this.effPercentage = effPercentage;
	}

	public void announce(int number) {
		if (global)
			boundary = (int) Math.floor((percentage / 100.0) * number);

		valueConstructor.announce(number);
	}

	public void mark(int number) {
		if (!global)
			boundary = (int) Math.floor((percentage / 100.0) * number);
	}

	public String next() {
		return valueConstructor.next();
	}

	public List<String> next(int number) {
		return valueConstructor.next(number);
	}

	/**
	 * Calculates normally distributed values around the mean 100 / percentage
	 * with a maximum deviation of half the mean. I.e. for a percentage of 25,
	 * quasi-normally distributed values in the range [2, 6] are being
	 * generated.</br> If the calculated offset exceeds the maximum possible
	 * offset for the current {@link #next} invocation, the remainder is stored
	 * and used as next offset. The result is being return as is.
	 * 
	 * @return offset for next value this PartialConstraint will be called for
	 */
	public int calcNextOffset(int max) {
		int result = 0;
		if (offsetRemainder > 0) {
			result = offsetRemainder;
			if (result > max) {
				offsetRemainder = result - max;
			} else {
				offsetRemainder = 0;
			}
		} else {
			double factor = rand.nextGaussian();
			if (factor < -1) {
				factor = -1;
			} else if (factor > 1) {
				factor = 1;
			}

			double baseOffset = 100.0 / (effPercentage != -1 ? effPercentage
					: percentage);
			double scale = baseOffset / 2;

			// Make sure 100% (and similar high percentages) are reached (reduce
			// scaling)
			// E.g. for 100%, always return 1 as offset
			if (baseOffset - scale < 1) {
				scale = baseOffset - 1;
			}

			result = (int) Math.round((float) baseOffset + scale * factor);
			if (result > max) {
				offsetRemainder = result - max;
			} else if (result < 1) {
				result = 1;
			}
		}
		return result;
	}

	@Override
	public String toString() {
		return String.format("%d%% as %s", percentage,
				valueConstructor.toString());
	}

	public boolean needsAnnounce() {
		return valueConstructor.needsAnnounce();
	}

	private void checkPercentage(int percent) {
		if (percent == 100) {
			String msg = String
					.format("PartialConstraint '%s' has a percentage of 100, that's not very meaningful.",
							toString());
			log.warn(msg);
		}
	}
}
